<?php

/**
 * Created by PhpStorm.
 * User: 彪
 * Date: 2016-5-29
 * Time: 19:37
 */
class Transaction_model extends Base_Model
{
    public function __construct()
    {
        $this->load->database();

    }

    public function detail($id)
    {
        $this->db->where('id', $id);
        $this->db->from('mod_payment_transaction');
        $query = $this->db->get()->row_array();

        return $query;
    }

    public function addOrder($data)
    {
        $this->db->trans_begin();

        $this->db->insert('app_order', $data);
        $insert_id = $this->db->insert_id();
        if ($insert_id > 0)
        {
            // 设置订单编号
            $orderNo = sprintf("%s%06d%s", date("Ymd"), $insert_id, date("Hi"));

            $hl = $this->exchange_rate();
            $moneyRMB =  sprintf("%.2f",$data['moneyTotal'] * $hl['bankConversionPri']/100);


            $row['moneyTotalRMB'] = $moneyRMB;
            $row['orderNo']=$orderNo;
            $this->db->set($row);
            $this->db->where(array('id'=>$insert_id));
            $this->db->update('app_order');


            // 记录订单日志
            $logObj['orderId'] =$insert_id;
            if (strtoupper($data['goodsType']) == 'TRACK')
                $logObj['log']  = "预订了路线订单";
            elseif (strtoupper($data['goodsType']) == 'ZIYING')
                 $logObj['log'] = "预订了自营项目订单";
            else
                $logObj['log'] = "预订了活动订单";
            $logObj['created'] = time();
            $this->addLog($logObj);
            if ($this->db->trans_status() === FALSE)
            {
                $this->db->trans_rollback();
            }
            else
            {
                $this->db->trans_commit();
            }
            
            $this->db->trans_begin();
            $this->db->where(array('uid'=>$data['uid']));
            $this->db->from('user_v2_account');
            $user = $this->db->get()->row_array();
            $u['countsOrder'] = $user['countsOrder']+1;
            $this->db->set($u);
            $this->db->where(array('uid'=>$user['uid']));
            $this->db->update('user_v2_account');


            $row = array(
                'status'    => 'UNPAID',
                'total_fee' => $moneyRMB,
                'body'      => $data['title'],
                'uid'       => $data['uid'],
                'shopId'    => $data['shopId'],
                'shopIdGroup'    => $data['shopId'],
                'created'   => time(),
                'changed'   => time(),
            );

            $this->db->insert('mod_payment_transaction', $row);
            $transId = $this->db->insert_id();

            if ($transId > 0)
            {
                $out_trade_no = sprintf("%s%s%06d", date("Ymd"), date("Hi"), $transId);
                $row['out_trade_no']=$out_trade_no;
                $this->db->set($row);
                $this->db->where(array('id'=>$transId));
                $this->db->update('mod_payment_transaction');
            }
            $this->updateCountsOrders($data['goodsType'],$insert_id);


            if ($this->db->trans_status() === FALSE)
            {
                $this->db->trans_rollback();
            }
            else
            {
                $this->db->trans_commit();
            }
        }




        return $transId;
    }


    public function detailBy($no)
    {
        $this->db->where('out_trade_no', $no);
        $this->db->from('mod_payment_transaction');
        $query = $this->db->get()->row_array();

        return $query;
    }

    public function notify_paid($id,$data)
    {


        $detail = $this->detail($id);
        $iResultCode = $detail['resultCode'];
        $iReturnCode = $detail['returnCode'];

        if ($iResultCode == 'SUCCESS' || $iReturnCode == 'SUCCESS')
            return;

        $row = array(
            'platform'      => $data['platform'],
            'status'        => 'PAID',
            'transactionId' => $data['transactionId'],
            'merchantId'    => $data['merchantId'],
            'resultCode'    => $data['resultCode'],
            'returnCode'    => $data['returnCode'],
            'changed'       => time()
        );

        $this->db->trans_begin();

        $this->db->set($row);
        $this->db->where(array('id'=>$id));
        $re = $this->db->update('mod_payment_transaction');

        if ($re > 0)
        {

            $orderdata = array(
                'status'  => 1,  // 已付款，待导游确认
                'changed' =>time(),
                'paidTime'=> time(),
            );
            $o_w = array(
                'transactionId'=>$id
            );
            $o_r =  $this->updateOrder($orderdata,$o_w);

            if($o_r)
            {
                $where = array('transactionId'=>$id);
                $orders = $this->getOrderBy($where);
                foreach ($orders as $rs)
                {
                    // 记录订单日志
                    $logObj['orderId'] = $rs['id'];
                    $logObj['log'] = '游客向哇吖支付成功';
                    $logObj['created'] = time();
                    $this->addLog($logObj);

                    // 通知玩伴和游客有新的支付预订
                    $shopId = $rs['shopId'];
                    $this->notice($rs['uid'],$shopId,$rs['moneyTotalRMB'],$rs['title']);
//                    // 更新路线/线路的订单预订数量
                    $this->updateCountsOrders($rs['goodsType'] ,$rs['goodsId']);
                }
            }
        }
        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
        }
        else
        {
            $this->db->trans_commit();
        }

//        $rows = DB::update()
//            ->set($row)
//            ->where('id', '=', $this->_nid)
//            ->execute();



    }

    /**
     * 更新订单
     *
     * @param $data
     * @param $where
     * @return CI_DB_active_record|CI_DB_result
     */
    public function updateOrder($data, $where)
    {
        $this->db->set($data);
        $this->db->where($where);
        return $this->db->update('app_order');
    }

    public function getOrderBy($data)
    {
        $this->db->select('id,uid,moneyTotalRMB,title,shopId,goodsType,goodsId');
        $this->db->from('app_order')->where($data);
        $data = $this->db->get()->result_array();
        return $data;
    }

    public function addLog($data)
    {
        return $this->db->insert('app_order_log', $data);
    }


    public function addNotice($send,$receive,$message)
    {
        $data = array(
            'sendUser'=>$send,
            'receiveUser'=>$receive,
            'type'=>0,
            'message'=>$message,
            'created'=>time(),
        );
        return $this->db->insert('mod_notice', $data);
    }


    public function updateCountsOrders ($type,$goodsId)
    {


        $table = '';
        switch ($type)
        {
            case 'TRACK':
                $this->db->where('goodsType =', 'TRACK');
                $this->db->where('goodsId  =', $goodsId);
                $this->db->where_in('status', array(1, 3, 99));
                $table = 'mod_track';
                break;

            case 'ACTIVITY':
                // 获取实际订单数
                $this->db->where('goodsType =', 'ACTIVITY');
                $this->db->where('goodsId  =', $goodsId);
                $this->db->where_in('status', array(1, 3, 99));
                $table = 'mod_activity';
                break;

            case 'ZIYING':
                // 获取实际订单数
                $this->db->where('goodsType =', 'ZIYING');
                $this->db->where('goodsId  =', $goodsId);
                $this->db->where_in('status', array(1, 3, 99));
                $table = 'mod_ziying';
                break;

            default:
                throw new Exception("无效 $type ");
        }
        $this->db->from('app_order');
        $counts =  $this->db->count_all_results(); // Pro
        echo $this->db->last_query();
//        var_dump($counts,1111);die;
        // $n 参数作废

        // 获取实际订单数

        $this->db->set(array('orders' => $counts));
        $this->db->where('id = ',$goodsId);
        $d  = $this->db->update("{$table}");
//        var_dump($d);
//        echo $this->db->last_query();
        return  $d;

    }

    public function notice($uid,$shopId,$money,$title){
        $tourist =$this->getUserInfoById($uid);
        $guider = $this->getUserInfoById($shopId);
        $tourist_name = $tourist['realName'];
        $guider_name = $guider['realName'];
        $tourist_web_notice = "您预订了".$guider_name."的《{$title}》，并支付了".($money/100)."元，您可以去个人中心里的预定记录中查看订单。";
        $guider_web_notice = $tourist_name."预订了您的《{$title}》的申请，请尽快前去个人中心预定记录的预定申请中处理。";
        $this->addNotice($uid, $uid, $tourist_web_notice);
        $this->addNotice($uid, $shopId, $guider_web_notice);
        $mobile =$guider['userPhone'];
        if($mobile != ""){
            $tpl_id = 1129823;
            $tpl_value = "#name1#=Hi&#name2#=tourist";
//            $sms_obj = new Util_YunPianSms();
            $this->load->library('Mysms');
//            $this->mysms->send_sms_to_user_id($tpl_id, $tpl_value, $mobile);
            $dat = $this->mysms->send_sms_to_user_id($tpl_id, $tpl_value, '15251540516');
            var_dump($dat);
        }
//        $mail = $guider['email'];
        $mail = '741024297@qq.com';
        if(!empty($mail)){
//            $addr = url::site("/guider/orders_request", 'http', FALSE);
            $addr = 'http://www.baidu.com';
            $body = <<<DOC
<meta charset="utf-8">
<style type="text/css">
body{ margin:0 auto; padding:0; font-family:'微软雅黑','Hiragino Sans GB', '华文细黑', 'STHeiti', 'Microsoft YaHei',
SimHei, 'Helvetica Neue', Helvetica, Arial, sans-serif;background-color:#fff; font-size:12px;}
a{line-height:22px; text-decoration:none;}
a:hover{text-decoration:underline;color:#489E85;}
td{font-family:'微软雅黑';}
</style>
<table width="800" border="0" align="center" cellpadding="0" cellspacing="0" style="font-family:'微软雅黑';">
<tbody>
<tr>
        <td>
             <table style="width:800px;height:149px;">
             <tbody>
            <tr>
            <td><img src="http://www.wayatrip.com/resource/images/mail-imgs2.png" style="width:800px;height:149px;"></td>
            </tr>
             </tbody></table>
       </td>
</tr>
<tr>
        <td>
             <table style="width:800px;height:20px;">
             <tbody>
            <tr>
            <td width="800" height="30"></td>
            </tr>
             </tbody></table>
       </td>
</tr>
<tr>
        <td>

            <table width="800" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#fff" height="74" style="font-family:'微软雅黑';">
              <tbody><tr>
                <td width="97" height="74" border="0" align="center" valign="middle" style="padding-left:20px;"><a href="http://www.wayatrip.com" target="_blank"><img src="http://www.wayatrip.com/resource/www/imgs/logo.png" alt="哇吖自由行" width="97" height="74" border="0"></a>
               </td>
                <td width="703" height="74" colspan="2" align="left" valign="middle" style="padding-left:30px;">
                <font style="font-size:30px;color:#489E85;"><strong>游客预定申请</strong></font>
                </td>
              </tr>
            </tbody></table>

        </td>
</tr>
<tr>
        <td>
             <table style="width:800px;height:20px;">
             <tbody>
            <tr>
            <td width="800" height="30"></td>
            </tr>
             </tbody></table>
       </td>
</tr>
<tr>
        <td>
             <table align="center" cellpadding="0" cellspacing="0" style="width:640px;height:150px;border:1px solid #96EDCC;border-radius:6px;
background-color:#96EDCC;color:#393939">
             <tbody>
            <tr>
            <td width="640" height="50" align="left" colspan="2" style="font-size:20px;vertical-align:middle;font-family:'微软雅黑';padding-left:20px;">
            <strong><font style="font-size:30px">{$tourist_name}</font>&nbsp;&nbsp;先生/女士预定了您的&nbsp;&nbsp;<font style="font-size:30px">{$title}</font>&nbsp;&nbsp;行程</strong></td>
            </tr>

             </tbody></table>
       </td>
</tr>
<tr>
        <td>
             <table style="width:800px;height:50px;">
             <tbody>
            <tr>
            <td width="800" height="50"></td>
            </tr>
             </tbody></table>
       </td>
</tr>
<tr>
       <td>
       <table align="center" cellpadding="0" cellspacing="0" style="width:200px;height:50px;border:1px solid #F05C92;border-radius:4px;
background-color:#F05C92;vertical-align:middle;">
             <tbody>
            <tr>
            <td style="font-size:20px;vertical-align:middle;font-family:'微软雅黑';padding-left:60px;width:200px;height:50px;">
            <a href="{$addr}" target="_blank" style="text-decoration:none;color:#fff;width:200px;height:50px;">处理申请</a>
            </td>
            </tr>
             </tbody></table>
       </td>

</tr>
<tr>
        <td>
             <table style="width:800px;height:30px;">
             <tbody>
            <tr>
            <td width="800" height="30"></td>
            </tr>
             </tbody></table>
       </td>
</tr>
<tr>
        <td>
             <table style="width:800px;height:50px;text-align:center;vertical-align:middle">
             <tbody>
            <tr>
            <td style="font-size:15px;">如无法点击，复制以下地址至浏览器打开<br/>{$addr}</td>
            </tr>
             </tbody></table>
       </td>
</tr>
<tr>
        <td>
             <table style="width:800px;height:30px;">
             <tbody>
            <tr>
            <td width="800" height="30"></td>
            </tr>
             </tbody></table>
       </td>
</tr>
<tr>
        <td>
             <table width="800" height="200" cellpadding="0" cellspacing="0" style="background-color:#252525;color:#fff;">
             <tbody>
            <tr>
            <td width="175" height="200"></td>
            <td>
            <table style="height:225px;width:200px;color:#fff;">
             <tbody>
            <tr>
            <td width="200" height="50" align="left" style="font-size:15px;vertical-align:middle;font-family:'微软雅黑';color:#fff;">联系我们</td>
            </tr>
            <tr>
            <td width="200" height="30" align="left" style="font-size:15px;vertical-align:middle;font-family:'微软雅黑';color:#fff;">国内：400-889-7955</td>
            </tr>
            <tr>
            <td width="200" height="30" align="left" style="font-size:15px;vertical-align:middle;font-family:'微软雅黑';color:#fff;">法国：+33666015304</td>
            </tr>
            <tr>
            <td width="200" height="30" align="left" style="font-size:15px;vertical-align:middle;font-family:'微软雅黑';color:#fff;">邮箱：info@wayatrip.com</td>
            </tr>
            <tr>
            <td width="200" height="60" align="left" ></td>
            </tr>
            </tbody></table>
           </td>
           <td>
            <table style="height:250px;width:200px;color:#fff;">
             <tbody>
            <tr>
            <td width="200" height="50" align="center" style="font-size:15px;vertical-align:middle;font-family:'微软雅黑';padding-top:10px;color:#fff;">官方微信<br/>wayaziyouxing</td>
            </tr>
            <tr>
            <td width="200" height="100" align="center"><img src="http://www.wayatrip.com/resource/www/imgs/erweima.jpg" style="height:100px;width:100px"></td>
            </tr>
            <tr>
            <td width="200" height="50" ></td>
            </tr>
            </tbody></table>
           </td>
           <td width="150" height="200"></td>
            </tr>
             </tbody></table>
       </td>
</tr>
</tbody></table>
DOC;
//            $body  = "{$tourist_name}先生/女士预订了您的{$title}的申请，请点击下方链接处理申请 ".url::site("/guider/orders_request", 'http', FALSE)."，如无法点击，请复制地址至浏览器打开。";
            return ;
            User_Subscribe::post_email($mail,'游客预定申请',$body);
        }
    }

    public function getUserInfoById($uid)
    {
        $key_info = array("telActive","identityErea_zhuanye", "identityErea_school","userIcon", "identityActive", "active", 'telCode', 'telNum', 'identityErea', 'identityName', 'identityPicture', 'email','mail', 'failMsg', 'utype');
        $key_user_info = array('userAge', 'nationality', 'language', 'introduction', 'resideCity', 'resideTime', 'country', 'code', 'rcity', 'addr', 'userGender','userPhone');


        $query = $this->db->query("select * from user_v2 as u1 LEFT JOIN user_v2_userinfo as u2 on u1.uid = u2.uid  WHERE u1.uid ={$uid}");
        $userInfo = $query->row_array();

        $baseInfo = array();
        foreach ($key_user_info as $v) {
            $baseInfo[$v] = empty($userInfo[$v]) ? '' : $userInfo[$v];
        }
        foreach ($key_info as $v) {
            $baseInfo[$v] = empty($userInfo[$v]) ? '' : $userInfo[$v];
        }

        if ($baseInfo['identityName'] == '留学生') {
            $data = explode('-|-', $baseInfo['identityErea']);
            $baseInfo['identityErea_zhuanye'] = empty($data[false]) ? '' : $data[false];
            $baseInfo['identityErea_school'] = empty($data[1]) ? '' : $data[1];
        }

        $lang = array();
        foreach (explode(',', $userInfo['language']) as $v) {
            if ($v == 1) {
                $lang[] = '中文';
            } elseif ($v == 2) {
                $lang[] = '法文';
            } elseif ($v == 3) {
                $lang[] = '英文';
            }
        }
        $baseInfo['language'] = $lang;

        $userFamily = empty($userInfo['userFamily']) ? '' : $userInfo['userFamily'];
        $userName = empty($userInfo['userName']) ? '' : $userInfo['userName'];
        $baseInfo['realName'] = $userFamily . $userName;

        return $baseInfo;
    }

}